package com.one.product;

import com.google.gson.Gson;
import com.one.DBUtil;
import com.one.product.model.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

//@WebServlet("/product_list.do")
public class ProductListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList<Product> list = new ArrayList<>(); // 使用Model泛型

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM tb_product ORDER BY create_time DESC LIMIT 10";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                Product product = new Product(); // 创建Product实例
                product.setDescription(rs.getString("description"));
                product.setName(rs.getString("name"));
                product.setId(rs.getInt("id"));
                product.setMarket_price(rs.getDouble("market_price")); // 确保列名正确
                product.setSell_price(rs.getDouble("sell_price")); // 确保列名正确
                product.setPicture(rs.getString("picture"));
                list.add(product); // 添加Model实例到列表中
            }

            Gson gson = new Gson();
            String result=gson.toJson(list);
            resp.setContentType("application/json");
            resp.setCharacterEncoding("utf-8");
            resp.getWriter().print(result);

        } catch (SQLException e) {
            throw new ServletException(e);
        } finally {
            DBUtil.closeResource(conn, ps, rs); // 确保在 finally 块中关闭资源
        }
    }
}
